package cn.actoncode.boot.framework.common.http.okhttp;

import cn.actoncode.boot.framework.common.exception.ServiceErrorException;
import cn.actoncode.boot.framework.common.http.RequestHttp;
import cn.actoncode.boot.framework.common.http.SimpleGetRequestExecutor;
import cn.actoncode.boot.framework.common.http.enums.PlatformType;
import cn.hutool.core.collection.CollUtil;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Map;

/**
 * .
 *
 * @author bin
 */
public class OkHttpSimpleGetRequestExecutor extends SimpleGetRequestExecutor<OkHttpClient, OkHttpProxyInfo> {
    public OkHttpSimpleGetRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    @Override
    public String execute(String uri, Map<String, String> headers, String queryParam, PlatformType platformType) throws ServiceErrorException, IOException {
        if (queryParam != null) {
            if (uri.indexOf('?') == -1) {
                uri += '?';
            }
            uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
        }
        Headers.Builder hb = new Headers.Builder();
        if (CollUtil.isNotEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                hb.add(entry.getKey(), entry.getValue());
            }
        }
        //得到httpClient
        OkHttpClient client = requestHttp.getRequestHttpClient();
        Request request = new Request.Builder().url(uri).headers(hb.build()).build();
        Response response = client.newCall(request).execute();
        return this.handleResponse(platformType, response.body().string());
    }

}
